<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import {
  ElButton,
  ElMessageBox,
  ElMessage,
  ElForm,
  ElFormItem,
  ElInput,
  ElRow,
  ElCol,
  ElUpload,
  ElIcon
} from 'element-plus'
import { Table } from '@/components/Table'
import {
  sendIndex,
  sendDel,
  sendEdit,
  deliverSetStatus,
  buchongAdd,
  ydhdsetStatus
} from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { ref, unref, reactive } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useCache } from '@/hooks/web/useCache'
import { useIcon } from '@/hooks/web/useIcon'
import { relative } from 'path'
const { wsCache } = useCache()
import { useAppStoreWithOut } from '@/store/modules/app'
const appStore = useAppStoreWithOut()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

const { push } = useRouter()
const { register, tableObject, methods } = useTable<TableData>({
  getListApi: sendIndex,
  delListApi: sendDel,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    filter: '{"status":"5"}',
    op: '{"status":"="}'
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods

getList()

const { emitter } = useEmitt()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'waybill',
    label: t('invoice.waybillNumber'),
    width: 200,
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'status',
    label: t('invoice.documentStatus'),
    table: {
      show: false
    },
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '仓库保存',
            value: 0
          },
          {
            label: '仓库提交',
            value: '1'
          },
          {
            label: '制单保存',
            value: '2'
          },
          {
            label: '制单提交',
            value: '3'
          },
          {
            label: '已审核',
            value: '4'
          },
          {
            label: '已到货',
            value: '5'
          }
        ]
      }
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'status_text',
    label: t('invoice.documentStatus'),
    search: {
      show: false
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'send_time',
    label: t('common.TimeText'),
    table: {
      show: false
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        type: 'date',
        valueFormat: 'YYYY-MM-DD'
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 6,
      show: true
    }
  },
  {
    field: 'client_code',
    width: '260px',
    label: t('customerManagement.customerNo'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'client_code',
    width: '260px',
    label: t('customerManagement.customerNo'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'fahuo',
    width: '260px',
    label: t('customerManagement.shipper'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'shouhuo',
    width: '260px',
    label: t('customerManagement.consignee'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'shouhuo_mobile',
    width: '260px',
    label: t('customerManagement.consigneePhone'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'placestart_text',
    width: '260px',
    label: t('router.origin'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'placeend_id',
    width: '260px',
    label: t('router.destination'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'transport_text',
    width: '260px',
    label: t('router.transport'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'submarket_text',
    width: '260px',
    label: t('router.distributionMarket'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'locationOfGoods',
    width: '260px',
    label: t('invoice.locationOfGoods'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'remark',
    width: '260px',
    label: t('invoice.productNameRemarks'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'receivingDate',
    width: '260px',
    label: t('invoice.receivingDate'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'deliveryTime',
    width: '260px',
    label: t('invoice.deliveryTime'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'weight',
    width: '260px',
    label: t('invoice.totalWeight'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'volume',
    width: '260px',
    label: t('invoice.totalVolume'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'units',
    width: '260px',
    label: t('invoice.totalNumberOfpices'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'quantity',
    width: '260px',
    label: t('invoice.packingQuantity'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'usd_value',
    width: '260px',
    label: t('invoice.usDollarCreditValue'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'insurance_rate',
    width: '260px',
    label: t('invoice.guaranteeRate'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pack_fee',
    width: '260px',
    label: t('invoice.packingCharges'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'base_freight',
    width: '260px',
    label: t('invoice.businessFloorFreight'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'short_fee_cny',
    width: '260px',
    label: t('invoice.shortdistancefee'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'other_fund',
    width: '260px',
    label: t('invoice.otherReceivables'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'agency_fund',
    width: '260px',
    label: t('invoice.invoicing'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'transport_price',
    width: '260px',
    label: t('invoice.fieghtPrice'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'total_fee',
    width: '260px',
    label: t('invoice.totalReceivableExpenses'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'paytype',
    width: '260px',
    label: t('invoice.paymentMethod'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'explain',
    width: '260px',
    label: t('invoice.illustrate'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'remark',
    width: '260px',
    label: t('userDemo.remark'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'imitate',
    width: '260px',
    label: t('invoice.whetherToImitateTheBrand'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'insurance_fee',
    width: '260px',
    label: t('invoice.insurancePremiumsReceivabl'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'action',
    width: '500px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const AddAction = () => {
  push('/logistics/arrivalNoteEndAdd')
}

const delLoading = ref(false)

const delData = async (row: TableData | null, multiple: boolean, rules: string) => {
  if (!checkRlues(rules)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: TableData, type: string, rules: string) => {
  if (!checkRlues(rules)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/logistics/arrivalNoteEnd${type}?id=${row.id}`)
      }
      break
    case 'Passed':
      {
        ElMessageBox.confirm(`是否${t('purchaseOrder.passedReview')}?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await ydhdsetStatus({
            ids: row.id,
            status: 1
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'ckSubmit':
      {
        ElMessageBox.confirm(`是否提交仓库?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await deliverSetStatus({
            ids: row.id,
            status: 1
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'zdSubmit':
      {
        ElMessageBox.confirm(`是否提交制单?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await deliverSetStatus({
            ids: row.id,
            status: 3
          })
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    default:
      break
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await sendEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}

const dialogTitle = ref('')

let editId = null
const addInfos = (row) => {
  dialogTitle.value = '补充信息'
  dialogVisible.value = true
  editId = row.id
}

const uploadForm = reactive({
  comment: null
})
const fileList: any = reactive([])
const getToken = wsCache.get('userInfo') ? wsCache.get('userInfo').token : ''

const uploadSuccess = (res, file, files) => {
  fileList.push({
    name: file.name,
    path: res.data.path,
    url: res.data.url
  })
}

const removeImg = (file, files) => {
  console.log('---remove---', file, files)
  let index = null
  fileList.forEach((item, i) => {
    if (item.name == file.name) {
      index = i
    }
  })
  fileList.splice(index, 1)
}

const saveImg = async () => {
  fileList.forEach((item, index) => {
    uploadForm[`img_${index + 1}`] = item.path
  })

  let res: any = await buchongAdd({
    deliver_id: editId,
    ...uploadForm
  })

  console.log('---res---', res)
  if (res && res.code == 1) {
    dialogVisible.value = false
    dialogTitle.value = ''
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <!-- <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton> -->
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true, '25-3')">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'Edit', '25-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '25-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <ElForm :model="uploadForm" label-width="auto">
      <ElRow>
        <ElCol :span="24">
          <ElFormItem label-width="100px" label="图片">
            <ElUpload
              action="http://liuzhen.wunuokeji.cn/api/deliver_attachment/uploadimg"
              v-model:file-list="fileList"
              :limit="4"
              accept="image/png, image/jpeg"
              :headers="{
                token: getToken
              }"
              list-type="picture-card"
              :on-success="uploadSuccess"
              :on-remove="removeImg"
            >
              <Icon class="pIcon" icon="ph:plus-thin" size="30" />
            </ElUpload>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label-width="100px" label="备注">
            <ElInput v-model="uploadForm.comment" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <template #footer>
      <ElButton type="primary" @click="saveImg">
        {{ t('exampleDemo.save') }}
      </ElButton>
    </template>
  </Dialog>
</template>
